import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mirror/AppStyle.dart';
import 'package:mirror/Util.dart';
import 'package:mirror/api/MessageApi.dart';
import 'package:mirror/api/UserApi.dart';
import 'package:mirror/bean/ChatBean.dart';
import 'package:mirror/bean/ChatBeanWebSocket.dart';
import 'package:mirror/bean/UserBean.dart';
import 'package:mirror/service/ProviderService.dart';
import 'package:mirror/service/WebSocketService.dart';
import 'package:mirror/widget/AvatarWidget.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ChatPage extends StatefulWidget {
  final String title;
  final String roomId;

  const ChatPage({super.key, required this.title, required this.roomId});

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  List<ChatBean> list = [];

  String time = "";
  var textController = TextEditingController();
  var listController = ScrollController();
  UserBean? mySelf;
  final _refreshController = RefreshController();
  int page = 1;

  @override
  void initState() {
    super.initState();

    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
        statusBarColor: Constant.mainColor,
        statusBarIconBrightness: Brightness.light));
    WebSocketService.addListener("chat", func: (messgae) {
      ChatBeanWebSocket msg = ChatBeanWebSocket.fromJson(jsonDecode(messgae));
      list.add(ChatBean(
          senderId: "${msg.senderId}",
          roomId: "${msg.roomId}",
          content: "${msg.content}",
          sentAt: "${msg.sentAt}",
          sentType: "${msg.sentType}",
          nickName: "${msg.nickName}",
          avatar: "${msg.avatar}"));
      listController.animateTo(listController.position.maxScrollExtent + 80,
          duration: const Duration(milliseconds: 200), curve: Curves.linear);
      setState(() {});
    });
    UserApi.getUser().then((value) {
      mySelf = value;
      setState(() {});
    });
    getHistory();
  }

  @override
  void dispose() {
    super.dispose();
    WebSocketService.removeListener("chat");
  }

  @override
  Widget build(BuildContext context) {
    var myData = Provider.of<ProviderData>(context);
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            Container(
                padding: const EdgeInsets.symmetric(vertical: 15),
                width: double.infinity,
                color: Constant.mainColor,
                child: Center(
                  child: Text(
                    widget.title,
                    style: const TextStyle(color: Colors.white),
                  ),
                )),
            Expanded(
              child: SmartRefresher(
                header: WaterDropMaterialHeader(
                  backgroundColor: Theme.of(context).primaryColor,
                ),
                controller: _refreshController,
                onRefresh: () {
                  refresh(isRefresh: true);
                },
                enablePullDown: true,
                child: ListView.builder(
                    controller: listController,
                    itemCount: list.length,
                    itemBuilder: (c, i) {
                      return Container(
                        padding: const EdgeInsets.symmetric(
                            vertical: 10, horizontal: 15),
                        child: Row(
                          children: [
                            Expanded(child: getListView(i, myData)),
                          ],
                        ),
                      );
                    }),
              ),
            ),
            Text(time),
            Container(
              padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
              decoration: BoxDecoration(
                  boxShadow: Constant.boxShadow, color: Colors.white),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                      child: Container(
                    padding:
                        const EdgeInsets.symmetric(horizontal: 5, vertical: 10),
                    decoration: BoxDecoration(
                        color: Colors.grey.shade200,
                        borderRadius: Constant.borderRadius),
                    child: TextField(
                      controller: textController,
                      decoration:
                          const InputDecoration.collapsed(hintText: "请输入内容"),
                      maxLines: 5,
                      minLines: 1,
                    ),
                  )),
                  const SizedBox(
                    width: 10,
                  ),
                  InkWell(
                    onTap: () async {
                      if (textController.text.isEmpty) {
                        Util.toast("请输入内容");
                        return;
                      }

                      await WebSocketService.send(json.encode({
                        "senderId": "${mySelf?.userUid}",
                        "roomId": widget.roomId,
                        "content": textController.text,
                        "sentType": "2",
                        "avatar": myData.userAvatar.isEmpty
                            ? "${mySelf?.userAvatar}"
                            : myData.userAvatar,
                        "nickName": "${mySelf?.nickName}"
                      }));
                      textController.clear();
                      setState(() {});
                    },
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 15, vertical: 10),
                      decoration: BoxDecoration(
                          color: Constant.mainColor,
                          borderRadius: Constant.borderRadius),
                      child: const Text(
                        "发送",
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  getListView(int i, ProviderData myData) {
    ChatBean data = list[i];
    if ("${mySelf?.userUid}" == data.senderId) {
      return Column(
        children: [
          Text("${data.sentAt}"),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Align(
                  alignment: Alignment.centerRight,
                  child: Column(
                    children: [
                      Text(
                        "${data.nickName}",
                        style: const TextStyle(fontSize: 12),
                      ),
                      const SizedBox(
                        height: 3,
                      ),
                      Container(
                        padding: const EdgeInsets.all(5),
                        decoration: BoxDecoration(
                            color: Constant.mainColor,
                            borderRadius: Constant.borderRadius),
                        child: Text(
                          "${data.content}",
                          style: const TextStyle(color: Colors.white),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              const SizedBox(
                width: 5,
              ),
              AvatarWidget(
                imageUrl: myData.userAvatar.isEmpty
                    ? "${data.avatar}"
                    : myData.userAvatar,
                size: 50,
                circular: 30,
              ),
            ],
          ),
        ],
      );
    } else {
      return Column(
        children: [
          Text("${data.sentAt}"),
          const SizedBox(
            height: 50,
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              AvatarWidget(
                imageUrl: '${data.avatar}',
              ),
              const SizedBox(
                width: 10,
              ),
              Expanded(
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "${data.nickName}",
                        style: const TextStyle(fontSize: 12),
                      ),
                      Container(
                        padding: const EdgeInsets.all(5),
                        decoration: BoxDecoration(
                            color: Constant.mainColor,
                            borderRadius: Constant.borderRadius),
                        child: Text(
                          "${data.content}",
                          style: const TextStyle(color: Colors.white),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      );
    }
  }

  Future<void> refresh({required bool isRefresh}) async {
    var lastTime = "${list.first.sentAt}";
    List<ChatBean>? l = await MessageApi.getHistory(
        roomId: widget.roomId,
        pageNumber: page,
        time: "${DateTime.parse(lastTime).millisecondsSinceEpoch}");
    if (l != null && l.isNotEmpty) {
      if (lastTime != "${l.first.sentAt}") {
        list.insertAll(0, l);
        setState(() {});
      }
    }
    _refreshController.refreshCompleted();
  }

  Future<void> getHistory() async {
    List<ChatBean>? l = await MessageApi.getHistory(
        roomId: widget.roomId,
        pageNumber: page,
        time: "${DateTime.now().millisecondsSinceEpoch}");
    if (l != null) {
      list.addAll(l);
      setState(() {});
    }
  }
}
